package com.zyinhao.controller;

import com.zyinhao.dto.UserReqDto;
import com.zyinhao.entity.User;
import com.zyinhao.service.UserService;
import com.zyinhao.vo.JsonResults;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping({ "/user" })
@Api(value = "UserController|一个用来测试restful的控制器")
public class UserController {

    static ArrayList<User> userList = new ArrayList<>();

    public UserController() {
        userList.add(new User("1","张三","zhang3", (int)(10+Math.random()*30),new Date()));
        userList.add(new User("2","李四","li4", (int)(10+Math.random()*30),new Date()));
        userList.add(new User("3","王五","wang5", (int)(10+Math.random()*30),new Date()));
        userList.add(new User("4","赵六","zhao6", (int)(10+Math.random()*30),new Date()));
    }

    @Autowired
    private UserService userService;

    /*****  restful api：查询(GET)、增(POST)、改(PUT)、删(DELETE)    *****/
    /**
     *
     * @param dto
     * @return
     * window.fetch('http://localhost:9002/user').then(response => response.json()).then(data => console.log(data))
     * window.fetch('http://localhost:8080/user/1').then(response => response.json()).then(data => console.log(data))
     * window.fetch('http://localhost:9002/user',{method: 'POST',headers: { 'Content-Type': 'application/json;charset=UTF-8' },body: JSON.stringify({'name':'aaa','code':'bbb'})}).then((response) => {return response.json();}).then(data => console.log(data))
     * window.fetch('http://localhost:9002/user/1',{method: 'PUT',headers: { 'Content-Type': 'application/json;charset=UTF-8' },body: JSON.stringify({'name':'update1'})}).then((response) => {return response.json();}).then(data => console.log(data))
     * window.fetch('http://localhost:9002/user/1',{method: 'delete'}).then((response) => {return response.json();}).then(data => console.log(data))
     */
    @RequestMapping(value = "",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询用户", notes="获取所有")
    public Object find(UserReqDto dto) {
        JsonResults<Object> result = new JsonResults<Object>();

        System.out.println("####controller:UserController:find:"+dto.toString());
        Map<String, Object> params = new HashMap<>();
        List<User> list = userService.find(params);

        result.setData(userList);
        return result;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取单个用户", notes="")
    public Object get(@PathVariable("id") String id) {
        JsonResults<Object> result = new JsonResults<Object>();

        System.out.println("####controller:UserController:get:");
        Map<String, Object> params = new HashMap<>();

        User user = null;
        for(int i=0; i<userList.size(); i++){
            if(id.equals(userList.get(i).getId())){
                user = userList.get(i);
            }
        }

        result.setData(user);
        return result;
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="新增用户", notes="没什么好说的")
    public Object add(@RequestBody User user) {
        JsonResults<Object> result = new JsonResults<Object>();

        user.setId("add:" + (int)(10+Math.random()*30));
        System.out.println("####controller:UserController:add:"+user.toString());
        userService.save(user);
        userList.add(user);
        return result;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ResponseBody
    @ApiOperation(value="修改用户", notes="这里是替换")
    public Object update(@RequestBody User user, @PathVariable("id") String id) {
        JsonResults<Object> result = new JsonResults<Object>();

        user.setId(id);
        System.out.println("####controller:UserController:update:"+user.toString());
        userService.update(user);
        for(int i=0; i<userList.size(); i++ ){
            if(id.equals(userList.get(i).getId())){
                user.setId(id);
                userList.set(i, user);
            }
        }
        return result;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    @ApiOperation(value="删除用户", notes="只能根据ID删除")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="path", name = "id", value = "用户ID", required = true, dataType = "String"),
    })
    public Object delete(@PathVariable("id") String id) {
        JsonResults<Object> result = new JsonResults<Object>();

        userService.delete(id);
        System.out.println("####controller:UserController:delete:"+id);
        for(int i=0; i<userList.size(); i++ ){
            if(id.equals(userList.get(i).getId())){
                userList.remove(i);
            }
        }
        return result;
    }

}